package com.zn.loading
{
    import flash.display.Loader;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.system.ApplicationDomain;
    import flash.system.LoaderContext;

    public class SWFLoader extends LoaderItem
    {

        private var _loader:Loader;
        _activeTypes("SWFLoader", SWFLoader);

        public function SWFLoader(url:String = null, name:String = null)
        {
            super(url, name);
        }

        protected override function init():void
        {
            super.init();

            _loader = new Loader();
            _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
            _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }
		
        protected override function completeHandler(event:Event):void
        {
            super.completeHandler(event);

            _content = _loader.content;

            loaderStatus = LoaderStatus.COMPLETED;
            dispatchEvent(new LoaderEvent(LoaderEvent.COMPLETE,this));
        }

        public override function load(flush:Boolean = false):void
        {
            if (loaderStatus != LoaderStatus.READY && !flush)
                return;

            super.load(flush);

            var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
            _loader.load(_urlRequest, context);
        }

        public function getClass(name:String):Class
        {
            var ad:ApplicationDomain = _loader.contentLoaderInfo.applicationDomain;
            if (ad.hasDefinition(name))
                return Class(ad.getDefinition(name));

            return null;
        }

        override public function unload():void
        {
			super.unload();
            if (_loader)
            {
                LoaderMax.removeLoaderItem(name, false);
				try
				{
					_loader.unloadAndStop(false);
				} 
				catch(error:Error) 
				{
					
				}
              
                _loader = null;
            }
        }
		
		override public function stop():void
		{
			super.stop();
			if (_loader)
			{
				try
				{
					_loader.close();
				} 
				catch(error:Error) 
				{
					
				}
			}
		}
		
		public override function pause():void
		{
			super.pause();
			
			if (_loader)
			{
				try
				{
					_loader.close();
				} 
				catch(error:Error) 
				{
					
				}
			}
		}

    }
}